import type {
  ComputeContext,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
} from '@fast-crud/fast-crud';

import { ref, unref } from 'vue';

import { compute } from '@fast-crud/fast-crud';

import { BaseEmployeeApi } from '#/api';
import { BaseRoleApi } from '#/api/basic/system/baseRole';
import { BaseOrgApi } from '#/api/basic/user/baseOrg';
import { ScopeTypeEnum } from '#/enums/base';
import { DictEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import {
  backendDict,
  createdTimeColumn,
  indexColumn,
  STATE_CONSTANT_DICT,
  transformQuery,
} from '#/plugins/fast-crud/common';

export function createCrudOptions(
  props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  const { createMessage } = useMessage();
  const selectedRowKeys = ref<string[]>([]);

  async function bindRole(flag: boolean, roleIdList: string[]) {
    const formData = props.context;
    formData.bindRoleIds = await (formData.scopeType === ScopeTypeEnum.EMPLOYEE
      ? BaseEmployeeApi.saveEmployeeRole({
          flag,
          roleIdList,
          employeeId: formData.employeeId,
        })
      : BaseOrgApi.saveOrgRole({
          flag,
          roleIdList,
          orgId: formData.orgId,
        }));

    createMessage.success('操作成功');
  }

  return {
    selectedRowKeys,
    crudOptions: {
      request: {
        pageRequest: BaseRoleApi.pageRequest,
        transformQuery: (query) => {
          const tq = transformQuery(query);

          tq.model.orgId = props.context.roleId;
          tq.model.scopeType = props.context.scopeType;
          return tq;
        },
      },
      actionbar: {
        buttons: {
          add: { show: false },
          bind: {
            type: 'primary',
            text: '批量绑定',
            click() {
              if (
                !unref(selectedRowKeys) ||
                unref(selectedRowKeys).length <= 0
              ) {
                createMessage.warning($t('common.tips.pleaseSelectTheData'));
                return;
              }
              bindRole(true, unref(selectedRowKeys));
            },
          },
          cancel: {
            danger: true,
            text: '批量取消',
            click() {
              if (
                !unref(selectedRowKeys) ||
                unref(selectedRowKeys).length <= 0
              ) {
                createMessage.warning($t('common.tips.pleaseSelectTheData'));
                return;
              }
              bindRole(false, unref(selectedRowKeys));
            },
          },
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
      },
      rowHandle: {
        width: 110,
        align: 'center',
        buttons: {
          edit: { show: false },
          copy: { show: false },
          view: { show: false },
          remove: { show: false },
          bind: {
            type: 'primary',
            danger: compute((context: ComputeContext) => {
              return !!props.context.bindRoleIds.includes(context.row.id);
            }),
            text: compute((context: ComputeContext) => {
              return props.context.bindRoleIds.includes(context.row.id)
                ? '解除绑定'
                : '绑定';
            }),
            click(context) {
              const flag = !props.context.bindRoleIds.includes(context.row.id);
              bindRole(flag, [context.row.id]);
            },
          },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        code: {
          title: $t('basic.system.baseRole.code'),
          type: 'text',
          column: { show: true },
        },
        name: {
          title: $t('basic.system.baseRole.name'),
          type: 'text',
          search: { show: true },
          column: { show: true },
        },
        category: {
          title: $t('basic.system.baseRole.category'),
          type: 'dict-radio',
          dict: backendDict(DictEnum.RoleCategoryEnum),
          search: { show: true },
        },
        state: {
          title: $t('basic.system.baseRole.state'),
          type: 'dict-radio',
          dict: STATE_CONSTANT_DICT,
          search: { show: true },
        },
        ...createdTimeColumn({}),
      },
    },
  };
}

export const frontRules = {
  addForm: {
    rules: {},
  },
  editForm: {
    rules: {},
  },
};
